﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.BackgroundTransfer;
using DBDataContext.Model;
using System.Windows.Media.Imaging;
using System.IO.IsolatedStorage;
using System.IO;
using System.Windows.Navigation;
using System.Diagnostics;
using MangaForYou.Class;

using Microsoft.Phone.Net.NetworkInformation;
using System.Xml.Linq;
namespace WolfGuy
{
    public partial class MainPage : PhoneApplicationPage
    {
        //IEnumerable<BackgroundTransferRequest> transferRequests;
        Manga manga = new Manga();
        bool isUpdating = false;
        //List<DownloadAction> lstDownloadActionStructure;

        public MainPage()
        {
            InitializeComponent();

            // Set the page DataContext property to the ViewModel.
            this.DataContext = App.ViewModel; 
            this.Loaded += new RoutedEventHandler(MangaInfoPage_Loaded);
        }

        void MangaInfoPage_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                if (App.ViewModel.AllChapters.Count == 0)
                {
                    this.stkNoData.Visibility = Visibility.Visible;
                    //MessageBox.Show("Truyện này chưa có dữ liệu, bạn có đồng ý tải dữ liệu không?", "Question", MessageBoxButton.OKCancel);
                }
                else
                {
                    this.stkNoData.Visibility = Visibility.Collapsed;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Gặp lỗi: " + ex.Message);
            }
        }
        protected override void OnNavigatedTo(NavigationEventArgs args)
        {
            try
            {
                //int mangaId = App.ViewModel.LoadMangaDefault().MangaId;

                //App.ViewModel.GetChapterListByMangaId(mangaId);

                //this.ListChapter.ItemsSource = App.ViewModel.AllChapters;
                //manga = App.ViewModel.GetMangaById(mangaId);

                int MangaId = 1;

                App.ViewModel.GetChapterListByMangaId(MangaId);

                //this.ListChapter.ItemsSource = App.ViewModel.AllChapters;
                manga = App.ViewModel.GetMangaById(MangaId);

                //this.imgManga.Source = new BitmapImage(new Uri("Images/"+manga.ImageName, UriKind.RelativeOrAbsolute));

                this.txtMangaName.Text = manga.Name;
                this.txtDescription.Text = manga.Description;
                if (manga.IsCompleted == false)
                {
                    this.txtIsCompleted.Text = "Trạng thái: Đang tiến hành.";
                }
                else
                {
                    this.txtIsCompleted.Text = "Trạng thái: Hoàn thành.";
                }

                //if ((App.Current as App).lstDownload.Count > 0)
                //{
                //    // When the page loads, refresh the list of file transfers.
                //    // InitialTransferStatusCheck();
                //    // UpdateUI();

                //    ////////// Remove event for request change progress
                //    if (BackgroundTransferService.Requests.Count() > 0)
                //    {
                //        foreach (var request in BackgroundTransferService.Requests)
                //        {
                //            request.TransferProgressChanged += new EventHandler<BackgroundTransferEventArgs>(transfer_TransferProgressChanged);
                //        }
                //    }
                //    ////////////////////
                //}
            }
            catch (System.OutOfMemoryException ex)
            {
                MessageBox.Show(ex.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        #region "For download function"
        /// <summary>
        /// this calls the UpdateRequestsList helper method to obtain 
        /// the current list of transfer requests. 
        /// Then, for each BackgroundTransferRequest object in the list,
        /// a handler for the TransferStatusChanged and TransferProgressChanged events 
        /// are assigned.
        /// </summary>
        private void InitialTransferStatusCheck()
        {
            UpdateRequestsList();

            //foreach (var transfer in transferRequests)
            foreach (var transfer in BackgroundTransferService.Requests)
            {
                transfer.TransferStatusChanged += new EventHandler<BackgroundTransferEventArgs>(transfer_TransferStatusChanged);
                transfer.TransferProgressChanged += new EventHandler<BackgroundTransferEventArgs>(transfer_TransferProgressChanged);
                ProcessTransfer(transfer);
            }
        }

        void transfer_TransferStatusChanged(object sender, BackgroundTransferEventArgs e)
        {
            ProcessTransfer(e.Request);
            //UpdateUI();
        }

        void transfer_TransferProgressChanged(object sender, BackgroundTransferEventArgs e)
        {
            //UpdateUI();
        }

        private void UpdateRequestsList()
        {
            // The Requests property returns new references, so make sure that
            // you dispose of the old refereneces to avoid memory leaks.
            if (BackgroundTransferService.Requests.Count() > 0)
            {
                foreach (var request in BackgroundTransferService.Requests)
                {
                    request.Dispose();
                }
            }

            // the Requests property returns a list of new BackgroundTransferRequest objects
            //transferRequests = BackgroundTransferService.Requests;
        }

        private void UpdateUI()
        {
            // Update the list of transfer requests
            UpdateRequestsList();

            // If there are 1 or more transfers, hide the "no transfers"
            // TextBlock. IF there are zero transfers, show the TextBlock.
            //if (transferRequests.Count<BackgroundTransferRequest>() > 0)
            //if (BackgroundTransferService.Requests.Count() > 0)
            //{
            //    // Search each request from list of transferRequests
            //    //foreach (var request in transferRequests)
            //    foreach (BackgroundTransferRequest request in BackgroundTransferService.Requests)
            //    {
            //        int index = 0;
            //        // Search list of DownloadAction to find down Index Item which need to update
            //        for (int i = 0; i <= (App.Current as App).lstDownload.Count - 1; i++)
            //        {
            //            if ((App.Current as App).lstDownload[i].Request.RequestId == request.RequestId)
            //            {
            //                index = i;
            //                break;
            //            }
            //        }
            //        if ((App.Current as App).lstDownload.Count() > 0)
            //        {
            //            UpdateUIFromIndexItem(request, (App.Current as App).lstDownload[index].IndexFromListBox);
            //        }
            //    }
            //}
        }

        /// <summary>
        /// Remove transfer request by Id
        /// </summary>
        /// <param name="transferID"></param>
        private void RemoveTransferRequest(string transferID)
        {
            // Use Find to retrieve the transfer request with the specified ID.
            BackgroundTransferRequest transferToRemove = BackgroundTransferService.Find(transferID);

            //Debug.WriteLine(transferToRemove.Tag);

            if (transferToRemove != null)
            {
                // Try to remove the transfer from the background transfer service.
                try
                {
                    transferToRemove.TransferStatusChanged -= new EventHandler<BackgroundTransferEventArgs>(transfer_TransferStatusChanged);
                    BackgroundTransferService.Remove(transferToRemove);
                }
                catch (Exception e)
                {
                    // Handle the exception.
                    MessageBox.Show(e.Message);
                }
            }
        }

        private void ProcessTransfer(BackgroundTransferRequest transfer)
        {
            // Update database
            int index = 0;
            // Search list of DownloadAction to find down Index Item which need to update
            //for (int i = 0; i <= (App.Current as App).lstDownload.Count - 1; i++)
            //{
            //    if ((App.Current as App).lstDownload[i].Request.RequestId == transfer.RequestId)
            //    {
            //        index = i;
            //        break;
            //    }
            //}

            switch (transfer.TransferStatus)
            {
                case TransferStatus.Transferring:
                    break;
                case TransferStatus.Completed:

                    // If the status code of a completed transfer is 200 or 206, the
                    // transfer was successful
                    if (transfer.StatusCode == 200 || transfer.StatusCode == 206)
                    {
                        //string tag = transfer.Tag;
                        //tag = tag.Substring(0, tag.LastIndexOf("."));
                        string[] param = transfer.Tag.Split('@');

                        // param[0] = chapterId
                        // param[1] = manga name
                        // param[2] = chapter file (Ex: Chapter_001.zip)

                        int chapterId = int.Parse(param[0]);
                        string mangaName = param[1];
                        string chapterFolder = param[2].Substring(0, param[2].LastIndexOf("."));

                        Chapter chapter = App.ViewModel.GetChaptersById(chapterId);

                        // if status of IsDownloaded is equal 2 -> update IsDownloaded to 1 and unzip file
                        if (chapter.IsDownloaded == 2)
                        {
                            App.ViewModel.UpdateIsDownloadedByChapterId(chapter.ChapterId);
                            ISHelper.WorkWithZipFile(transfer.Tag);
                        }
                        /////////////////////

                        // Remove the transfer request in order to make room in the 
                        // queue for more transfers. Transfers are not automatically
                        // removed by the system.
                        RemoveTransferRequest(transfer.RequestId);

                        // Remove DownloadAction item, to make sure list of DownloadAction doest
                        // not have one item twice.
                        // Must put in last of block
                        RemoveDownloadActionFromList(transfer.RequestId);
                    }
                    else if (transfer.StatusCode == 0)
                    {
                        // StatusCode = 0: request is removed from BackgroundTransferService

                        // Do something if you want
                    }
                    else
                    {
                        // This is where you can handle whatever error is indicated by the
                        // StatusCode and then remove the transfer from the queue. 
                        RemoveTransferRequest(transfer.RequestId);

                        if (transfer.TransferError != null)
                        {
                            // Handle TransferError if one exists.


                        }
                    }
                    break;
                case TransferStatus.WaitingForExternalPower:
                    {
                        //MessageBox.Show("The request is waiting for external power to be connected.");
                        MessageBox.Show("The request is waiting for external power to be connected.");
                        DownloadError(transfer, index);
                        break;
                    }

                case TransferStatus.WaitingForExternalPowerDueToBatterySaverMode:
                    {
                        //WaitingForWiFi = true;
                        MessageBox.Show("The request is waiting for the device to be connected to external power because the user has enabled Battery Saver mode on this device");
                        DownloadError(transfer, index);
                        break;
                    }

                case TransferStatus.WaitingForNonVoiceBlockingNetwork:
                    {
                        MessageBox.Show("This device does not have wifi or network connection.");
                        DownloadError(transfer, index);
                        break;
                    }

                case TransferStatus.WaitingForWiFi:
                    {
                        MessageBox.Show("This device does not have wifi or  network connection.");
                        DownloadError(transfer, index);
                        break;
                    }
            }
        }


        // Called when download error
        private void DownloadError(BackgroundTransferRequest transfer, int index)
        {
            try
            {

                string[] param = transfer.Tag.Split('@');

                // param[0] = chapterId
                // param[1] = manga name
                // param[2] = chapter file (Ex: Chapter_001.zip)

                int chapterId = int.Parse(param[0]);
                string mangaName = param[1];
                string chapterFolder = param[2].Substring(0, param[2].LastIndexOf("."));

                // Update 
                App.ViewModel.UpdateNeedToDownloadByChapterId(chapterId);

                // Remove request
                RemoveTransferRequest(transfer.RequestId);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        // Only called when click download button
        private bool downloadChapter(Chapter chapter)
        {

            // The following code goes here.
            // Check to see if the maximum number of requests per app has been exceeded.
            if (BackgroundTransferService.Requests.Count() == 3)
            {
                // Note: Instead of showing a message to the user, you could store the
                // requested file URI in isolated storage and add it to the queue later.
                // MessageBox.Show("The maximum number of background file transfer requests for this application has been exceeded. ");
                MessageBox.Show("Chỉ có thể download cùng lúc 3 chapter. Vui lòng chờ.");
                return false;
            }

            // Get the URI of the file to be transferred from the Tag property
            // of the button that was clicked.
            //string transferFileName = ((Button)sender).Tag as string;
            string transferFileName = chapter.ChapterFileLink;
            Uri transferUri = new Uri(Uri.EscapeUriString(transferFileName), UriKind.RelativeOrAbsolute);


            // Create the new transfer request, passing in the URI of the file to 
            // be transferred.
            BackgroundTransferRequest transferRequest = new BackgroundTransferRequest(transferUri);

            // Set the transfer method. GET and POST are supported.
            transferRequest.Method = "GET";

            // Get the file name from the end of the transfer URI and create a local URI 
            // in the "transfers" directory in isolated storage.
            string downloadFile = transferFileName.Substring(transferFileName.LastIndexOf("/") + 1);
            // file name
            //string fileName = "@" + manga.Name + "@" + downloadFile;
            string fileName = String.Format("{0}@{1}@{2}", chapter.ChapterId, manga.FolderName, downloadFile);
            Uri downloadUri = new Uri("shared/transfers/" + fileName, UriKind.RelativeOrAbsolute);
            transferRequest.DownloadLocation = downloadUri;

            // Pass custom data with the Tag property. In this example, the friendly name
            // is passed.
            transferRequest.Tag = fileName;

            // If the Wi-Fi-only check box is not checked, then set the TransferPreferences
            // to allow transfers over a cellular connection.
            //if (wifiOnlyCheckbox.IsChecked == false)
            //{
            //    transferRequest.TransferPreferences = TransferPreferences.AllowCellular;
            //}
            //if (externalPowerOnlyCheckbox.IsChecked == false)
            //{
            //    transferRequest.TransferPreferences = TransferPreferences.AllowBattery;
            //}
            //if (wifiOnlyCheckbox.IsChecked == false && externalPowerOnlyCheckbox.IsChecked == false)
            //{
            //    transferRequest.TransferPreferences = TransferPreferences.AllowCellularAndBattery;
            //}

            //transferRequest.TransferPreferences = TransferPreferences.AllowBattery; v1.2
            transferRequest.TransferPreferences = TransferPreferences.AllowCellularAndBattery; // v1.2

            // Add the transfer request using the BackgroundTransferService. Do this in 
            // a try block in case an exception is thrown.
            try
            {
                BackgroundTransferService.Add(transferRequest);
                transferRequest.TransferStatusChanged += new EventHandler<BackgroundTransferEventArgs>(transfer_TransferStatusChanged);
                transferRequest.TransferProgressChanged += new EventHandler<BackgroundTransferEventArgs>(transfer_TransferProgressChanged);
                ProcessTransfer(transferRequest);

                return true;
            }
            catch
            {
                // Remove request if something wrong
                foreach (var request in BackgroundTransferService.Requests)
                {
                    if (request.RequestUri == transferRequest.RequestUri)
                    {
                        BackgroundTransferService.Remove(request);
                        break;
                    }
                }
                return false;

            }
        }
        #endregion

        #region "Work with file"
        private string GetFileNameFromFile(string fileName)
        {
            try
            {
                //return fileName.Substring(0, fileName.LastIndexOf("."));
                int indexOfSplash = 0;
                int indexOfAt = 0;
                int indexOfDot = 0;

                indexOfSplash = fileName.LastIndexOf("/");
                indexOfAt = fileName.LastIndexOf("@");
                indexOfDot = fileName.LastIndexOf(".");

                return fileName.Substring(0, indexOfSplash + 1) + fileName.Substring(indexOfAt + 1, indexOfDot - indexOfAt - 1);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            return null;
        }



        private string GetPathOfChapterFromRequestTag(string fileName)
        {
            try
            {
                //return fileName.Substring(0, fileName.LastIndexOf("."));
                int indexOfSplash = 0;
                int indexOfAt = 0;
                int indexOfDot = 0;

                indexOfSplash = fileName.LastIndexOf("/");
                indexOfAt = fileName.LastIndexOf("@");
                indexOfDot = fileName.LastIndexOf(".");

                return fileName.Substring(0, indexOfSplash + 1) + fileName.Substring(indexOfAt + 1, indexOfDot - indexOfAt - 1);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            return null;
        }

        private string GetMangaNameFromRequestTag(string fileName)
        {
            try
            {
                //return fileName.Substring(0, fileName.LastIndexOf("."));
                int indexOfSplash = 0;
                int indexOfAt = 0;

                indexOfSplash = fileName.LastIndexOf("/");
                indexOfAt = fileName.LastIndexOf("@");

                return fileName.Substring(indexOfSplash + 1, indexOfAt - indexOfSplash - 1);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            return null;
        }
        #endregion


        private void RemoveDownloadActionFromList(string requestId)
        {
            //int index = -1;
            //for (int i = 0; i <= (App.Current as App).lstDownload.Count - 1; i++)
            //{
            //    if ((App.Current as App).lstDownload[i].Request.RequestId == requestId)
            //    {
            //        index = i;
            //        break;
            //    }

            //}

            //if (index >= 0)
            //    (App.Current as App).lstDownload.RemoveAt(index);
        }

        //private void UpdateUIFromIndexItem(BackgroundTransferRequest request, int index)
        //{
        //    try
        //    {
        //        // Get item from control by usiong FindAnchestor
        //        ListBoxItem lstItem = (ListBoxItem)ListChapter.ItemContainerGenerator.ContainerFromIndex(index);

        //        TextBlock txtProgressInfo = new TextBlock();
        //        UIHelper.GetChildByName(lstItem, "txtProgressInfo", ref txtProgressInfo);
        //        if (request.BytesReceived > 0)
        //        {
        //            txtProgressInfo.Text = String.Format("Progress: {0}/{1} KB.",
        //                ((decimal)(request.BytesReceived / 1024)).ToString(),
        //                ((decimal)(request.TotalBytesToReceive / 1024)).ToString());
        //        }
        //        else
        //        {
        //            txtProgressInfo.Text = String.Format("Progress: Connecting to server...");
        //        }

        //        txtProgressInfo.Visibility = Visibility.Visible;

        //        Button btnStopDownload = new Button();
        //        UIHelper.GetChildByName(lstItem, "btnStopDownload", ref btnStopDownload);
        //        btnStopDownload.Visibility = Visibility.Visible;

        //        Button btnDownload = new Button();
        //        UIHelper.GetChildByName(lstItem, "btnDownload", ref btnDownload);
        //        btnDownload.Visibility = Visibility.Collapsed;
        //    }
        //    catch (Exception ex)
        //    {
        //        //MessageBox.Show(ex.Message);
        //    }
        //}


        #region "DONT USE THEM IN THIS PROJECT"
        private List<FrameworkElement> GetChildren(FrameworkElement element, ref List<FrameworkElement> list)
        {
            int count = VisualTreeHelper.GetChildrenCount(element);

            for (int i = 0; i < count; i++)
            {
                FrameworkElement child = VisualTreeHelper.GetChild(element, i) as FrameworkElement;

                if (child != null)
                {
                    // Do anything with child control here

                    ////////////////////

                    GetChildren(child, ref list);
                }
            }

            return list;
        }
        #endregion

        private void btnDownload_Click(object sender, RoutedEventArgs e)
        {
            if ((App.Current as App).isAutoDownload == true)
            {
                MessageBox.Show("Bạn đang ở chế độ tải tự động nên không thể tải nội dung này.");
                return;
            }

            var ni = NetworkInterface.NetworkInterfaceType;

            //if (NetworkInterface.GetIsNetworkAvailable() == false)
            if (ni == NetworkInterfaceType.None)
            {
                MessageBox.Show("Bạn không có kết nối internet. Vui lòng thử lại.");
                return;
            }

            try
            {
                Button button = (Button)sender;

                // Get item from control by usiong FindAnchestor
                ListBoxItem lstItem = UIHelper.FindAnchestor<ListBoxItem>(button);
                int index = this.ListChapter.ItemContainerGenerator.IndexFromContainer(lstItem);
                Chapter chapter = (Chapter)this.ListChapter.Items[index];

                // If this chapter is not downloaded (IsDownloaded = 0), start to download it
                if (chapter.IsDownloaded == 0)
                {
                    MessageBoxResult msgResult = MessageBox.Show("Bạn có muốn tải nội dung này?", "Xác nhận", MessageBoxButton.OKCancel);
                    if (msgResult == MessageBoxResult.OK)
                    {
                        if (downloadChapter(chapter))
                        {
                            App.ViewModel.UpdateDownloadingById(chapter.ChapterId);
                        }
                        else
                        {
                            MessageBox.Show("Không thể tải nội dung này. Vui lòng thử lại.");
                        }
                    }
                }
                else
                {
                    // Logic was wrong if code jump here
                    MessageBox.Show("Logic was wrong");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Lỗi xảy ra khi download: " + ex.Message);
            }
        }

        private void btnMove_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Button btnMove = (Button)sender;

                //ListBoxItem lstItem = UIHelper.FindAnchestor<ListBoxItem>(btnMove);
                //int index = this.ListChapter.ItemContainerGenerator.IndexFromContainer(lstItem);
                //Chapter chapter = (Chapter)this.ListChapter.Items[index];
                int chapterId = int.Parse(btnMove.Tag.ToString());
                Chapter chapter = App.ViewModel.GetChaptersById(chapterId);

                string strUri = String.Format("/ContentPage.xaml?mangaName={0}&chapterId={1}&chapterFileName={2}&curIndex={3}", manga.FolderName, chapter.ChapterId, chapter.ChapterFileName, chapter.CurrentIndex);
                NavigationService.Navigate(new Uri(strUri, UriKind.Relative));


                ////////// Remove event for request change progress
                //foreach (var request in BackgroundTransferService.Requests)
                //{
                //    request.TransferProgressChanged -= new EventHandler<BackgroundTransferEventArgs>(transfer_TransferProgressChanged);
                //}
                ////////////////////
            }
            catch (Exception ex)
            {
                MessageBox.Show("Lỗi xảy ra khi chuyển trang: " + ex.Message);
            }
        }


        // Delete chapter's files in Isolated Storage 
        private void btnDelete_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                MessageBoxResult msgResult = MessageBox.Show("Bạn có chắc chắn muốn xóa nội dung này?", "Xác nhận", MessageBoxButton.OKCancel);
                if (msgResult == MessageBoxResult.OK)
                {

                    // Delete file by using manga folder name and chapter file name
                    Button btnDelete = (Button)sender;

                    int chapterID = (int)btnDelete.Tag;

                    //ListBoxItem lstItem = UIHelper.FindAnchestor<ListBoxItem>(btnDelete);
                    //int index = this.ListChapter.ItemContainerGenerator.IndexFromContainer(lstItem);
                    //Chapter chapter = (Chapter)this.ListChapter.Items[index];
                    Chapter chapter = App.ViewModel.GetChaptersById(chapterID);
                    string mangaFolderName = manga.FolderName;
                    string chapterFileName = chapter.ChapterFileName;

                    // Call delete function
                    DeleteFiles(mangaFolderName, chapterFileName);

                    // Update database by using chapterId
                    //App.ViewModel.UpdateIsDownloadedByChapterId(chapter.ChapterId);
                    App.ViewModel.UpdateNeedToDownloadByChapterId(chapterID);
                    App.ViewModel.UpdateCurrentIndexByChapterID(chapterID, 0);
                    // Enable Download Button
                    //Button btnDownload = new Button();
                    //UIHelper.GetChildByName<Button>(lstItem, "btnDownload", ref btnDownload);
                    //btnDownload.IsEnabled = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Lỗi xảy ra khi xóa dữ liệu: " + ex.Message);
            }
        }

        private void DeleteFiles(string mangaFolderName, string chapterFileName)
        {
            using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
            {
                string strPattern = String.Format("Shared/Download/{0}/{1}", mangaFolderName, chapterFileName);

                // Delete all files in directory folder
                foreach (string file in isf.GetFileNames(strPattern + "/*"))
                {
                    //fileList.Add((strPattern + directory + "/" + file));
                    isf.DeleteFile(strPattern + "/" + file);
                }

                // Delete all files in sub folder(s)
                foreach (string directory in FindingExistingFilesAndDirectories.GetAllDirectories(strPattern + "/*", isf))
                {
                    foreach (string file in isf.GetFileNames(strPattern + "/" + directory + "/*"))
                    {
                        //fileList.Add((strPattern + directory + "/" + file));
                        isf.DeleteFile(strPattern + "/" + directory + "/" + file);
                    }
                    // Delete sub folder
                    isf.DeleteDirectory(strPattern + "/" + directory);
                }
                // Delete directory folder
                isf.DeleteDirectory(strPattern);
                isf.Dispose();
            }
        }

        private void ApplicationBarIconButton_Click(object sender, EventArgs e)
        {
            MessageBoxResult msgResult = MessageBox.Show("All requests will be removed when you go back Home Page, do you really want to go?", "Confirm", MessageBoxButton.OKCancel);
            if (msgResult == MessageBoxResult.OK)
            {
                foreach (BackgroundTransferRequest request in BackgroundTransferService.Requests)
                {
                    //request.Dispose();
                    BackgroundTransferService.Remove(request);

                }
                string strUri = String.Format("/DirectoryPage.xaml");
                NavigationService.Navigate(new Uri(strUri, UriKind.Relative));
            }
        }

        private void downloadPageButton_Click(object sender, EventArgs e)
        {
            string strUri = String.Format("/DownloadPage.xaml");
            NavigationService.Navigate(new Uri(strUri, UriKind.Relative));
        }

        private void aboutPageButton_Click(object sender, EventArgs e)
        {
            string strUri = String.Format("/AboutPage.xaml");
            NavigationService.Navigate(new Uri(strUri, UriKind.Relative));
        }

        private void imgDownloadIcon_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            try
            {
                if (isUpdating == true)
                    return;

                isUpdating = true;
                WebClient client = new WebClient();
                List<String> listOfQuery = new List<string>();
                //client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
                client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
                Uri xmlUrl = new Uri(manga.DataLinkDownload, UriKind.RelativeOrAbsolute);
                //client.OpenReadAsync(xmlUrl);
                client.DownloadStringAsync(xmlUrl);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Gặp lỗi: " + ex.Message);
                isUpdating = false;
            }
        }

        void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            try
            {
                //Stream str = e.Result;
                string str = e.Result;

                XDocument xDoc = XDocument.Parse(str);

                List<XElement> lstChapterInfo =
                    (from chapters in xDoc.Descendants("Chapters").Descendants("ChapterGroup")
                     select chapters).ToList();

                XElement eleFolderName =
                    (from link in xDoc.Descendants("Setting").Descendants("MangaFolderName")
                     select link).First();

                string strFolderName = eleFolderName.Value;

                App.ViewModel.UpdateMangaFolderName(manga.MangaId, strFolderName);

                foreach (var chap in lstChapterInfo)
                {
                    int startNum = 0;
                    int endNum = 0;
                    string prefix = "";

                    startNum = int.Parse(chap.Element("StartNumber").Value);
                    endNum = int.Parse(chap.Element("EndNumber").Value);
                    prefix = chap.Element("Prefix").Value;

                    App.ViewModel.InsertChapters(manga, prefix, startNum, endNum, strFolderName);
                }

                App.ViewModel.GetChapterListByMangaId(manga.MangaId);

                this.stkNoData.Visibility = Visibility.Collapsed;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                isUpdating = false;
            }
        }
    }
}